import { PropsWithChildren, useEffect } from "react";
import { SiderBar } from "../components/SiderBar";
import { useLegalSearchStore } from "../store";
import { LegalSearchIndex } from "./LegalSearch/LegalSearchIndex";
import { LegalSearchInfo } from "./LegalSearch/LegalSearchInfo";
import {
  fetchCreateChat,
  fetchKgSearchLaw,
} from "@/api/server/recommend_question";

interface ILegalSearchProps {
  className?: string;
}
export function LegalSearch(props: PropsWithChildren<ILegalSearchProps>) {
  const collapse = useLegalSearchStore((state) => state.collapse);
  const list = useLegalSearchStore((state) => state.list);
  const activeKey = useLegalSearchStore((state) => state.activeKey);
  const setActiveKey = useLegalSearchStore((state) => state.setActiveKey);
  const setTabType = useLegalSearchStore((state) => state.setTabType);
  const setFormValues = useLegalSearchStore((state) => state.setFormValues);
  const setCollapse = useLegalSearchStore((state) => state.setCollapse);
  const refreshList = useLegalSearchStore((state) => state.refreshList);
  const listType = useLegalSearchStore((state) => state.listType);
  const listSearch = useLegalSearchStore((state) => state.listSearch);
  const setListType = useLegalSearchStore((state) => state.setListType);
  const setListSearch = useLegalSearchStore((state) => state.setListSearch);

  const onSubmit = async (str: string, formValues: any, type: string) => {
    // setActiveKey("123");
    // const res = await fetchKgSearchLaw({
    //   keyword: str,
    // });

    console.log(str, formValues, type);
    const res = await fetchCreateChat({
      user_name: "test",
      sender: "user",
      message: str,
      type: "Law",
    });

    const chat_id = res.data.chat_id;
    refreshList();
    setFormValues(formValues);
    setTabType(type);
    setActiveKey(chat_id);
  };

  useEffect(() => {
    refreshList();
  }, []);

  return (
    <div className="flex flex-row h-full">
      <SiderBar
        type="doc-generation"
        list={list}
        setListSearch={setListSearch}
        setListType={setListType}
        listSearch={listSearch}
        listType={listType}
        collapse={collapse}
        refreshList={refreshList}
        onSetActiveKey={(k) => {
          setActiveKey("");

          setTimeout(() => {
            setActiveKey(k);
            setFormValues({});
            setTabType("1");
          }, 50);
        }}
        onSetCollapse={setCollapse}
        activeKey={activeKey}
      />
      <div className="flex-1 min-w-0 PageContent flex flex-col items-center">
        {activeKey ? (
          <div className="w-full h-full flex flex-col">
            <LegalSearchInfo infoKey={activeKey} />
          </div>
        ) : (
          <div className="w-[84%] h-full flex flex-col">
            <LegalSearchIndex onSubmit={onSubmit} />
          </div>
        )}
      </div>
    </div>
  );
}
